package com.learn.demo.netty.tcp.protocol;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * MyServerHandler
 *
 * @author banjiawei
 * @date 2022/01/15
 */
@Slf4j
public class MyServerHandler extends SimpleChannelInboundHandler<Message> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Message message) throws Exception {
        log.info("=========================================================================");
        String msg = new String(message.getContent(), StandardCharsets.UTF_8);
        log.info("服务端收到消息：[{}]", msg);
        log.info("=========================================================================\r\n");

        String res = "服务器：客户端，这里是服务器，已收到消息";
        byte[] bytes = res.getBytes(StandardCharsets.UTF_8);
        Message resMsg = new Message();
        resMsg.setLength(bytes.length);
        resMsg.setContent(bytes);
        channelHandlerContext.writeAndFlush(resMsg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.channel().close();
    }
}
